import pandas as pd
import numpy as np
import os

def reclassify_users():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 读取合并后的数据
    df = pd.read_csv(os.path.join(current_dir, 'analysis_results', 'merged_cluster_sentiment_results.csv'))
    
    # 计算每个用户的特征统计
    user_stats = df.groupby('user_id').agg({
        'sentiment_score': ['mean', 'count'],
        'like_counts': 'mean',
        'reply_counts': 'mean',
        'word_count': 'mean'
    }).reset_index()
    
    # 重命名列
    user_stats.columns = ['user_id', 'sentiment_mean', 'comment_count', 
                         'avg_likes', 'avg_replies', 'avg_word_count']
    
    # 计算互动影响力
    user_stats['interaction_score'] = (user_stats['avg_likes'] + user_stats['avg_replies']) / 2
    
    # 计算评论活跃度（使用评论数量作为代理）
    user_stats['activity_score'] = user_stats['comment_count']
    
    # 标准化特征
    from sklearn.preprocessing import StandardScaler
    scaler = StandardScaler()
    user_stats[['interaction_score', 'activity_score']] = scaler.fit_transform(
        user_stats[['interaction_score', 'activity_score']])
    
    # 根据报告中的标准重新分类
    def classify_user(row):
        # 高活跃/高影响力用户群
        if row['activity_score'] > 3 or row['interaction_score'] > 3:
            return 2  # 高活跃/高影响力用户群
        
        # 积极用户群
        elif row['sentiment_mean'] > 0.5:
            return 0  # 积极用户群
        
        # 消极用户群
        else:
            return 1  # 消极用户群
    
    # 应用分类
    user_stats['new_cluster'] = user_stats.apply(classify_user, axis=1)
    
    # 将新的分类结果合并回原始数据
    df = pd.merge(df, user_stats[['user_id', 'new_cluster']], on='user_id', how='left')
    
    # 删除不需要的列
    columns_to_drop = [
        'comment_id', 'created_at', 'user_id', 'user_name', 'user_city',
        'content', 'cluster', 'cleaned_text', 'segmented_text'
    ]
    df = df.drop(columns=columns_to_drop)
    
    # 确保输出目录存在
    output_dir = os.path.join(current_dir, 'analysis_results')
    os.makedirs(output_dir, exist_ok=True)
    
    # 保存结果
    df.to_csv(os.path.join(output_dir, 'reclassified_users_simplified.csv'), index=False)
    
    # 生成分类统计报告
    cluster_names = {
        0: '积极用户群',
        1: '消极用户群',
        2: '高活跃/高影响力用户群'
    }
    
    with open(os.path.join(output_dir, 'reclassification_report.txt'), 'w', encoding='utf-8') as f:
        f.write("用户重新分类报告\n")
        f.write("="*50 + "\n\n")
        
        f.write("1. 群体划分概述\n")
        for cluster_id, cluster_name in cluster_names.items():
            count = len(user_stats[user_stats['new_cluster'] == cluster_id])
            percentage = (count / len(user_stats)) * 100
            f.write(f"- {cluster_name}: {count}人 ({percentage:.1f}%)\n")
        
        f.write("\n2. 群体特征统计\n")
        for cluster_id, cluster_name in cluster_names.items():
            cluster_data = user_stats[user_stats['new_cluster'] == cluster_id]
            f.write(f"\n{cluster_name}:\n")
            f.write(f"- 平均情绪得分: {cluster_data['sentiment_mean'].mean():.3f}\n")
            f.write(f"- 平均互动影响力: {cluster_data['interaction_score'].mean():.3f}\n")
            f.write(f"- 平均评论数量: {cluster_data['comment_count'].mean():.1f}\n")
            f.write(f"- 平均点赞数: {cluster_data['avg_likes'].mean():.1f}\n")
            f.write(f"- 平均回复数: {cluster_data['avg_replies'].mean():.1f}\n")

if __name__ == "__main__":
    reclassify_users() 